/*
 * @FileName: [FileUploadControlloer.java]
 * 
 * @Package com.bcinfo.upp.admin.controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 44 $ $LastChangedDate: 2013-10-12 10:19:57 +0800 (星期六, 12 十月 2013) $ $LastChangedBy: wanggc $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author luojianhong
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bcinfo.iccard.admin.common.ModuleEnum;
import com.bcinfo.iccard.admin.util.DataMatrixUtil;
import com.bcinfo.iccard.admin.util.ExcelUtil;
import com.bcinfo.iccard.admin.util.TxtUtil;
import com.bcinfo.iccard.admin.util.UploaderHelper;
import com.bcinfo.iccard.exception.IccardDatabaseException;
import com.bcinfo.iccard.service.RechargeableCardService;
import com.bcinfo.upp.exception.UppDataBaseException;

/**
 * 文件上传控制器 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 提供公共的控制器方法、属性
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 * public class XxxControler extends AbstractController
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/common/fileUpload")
public class FileUploadController extends AbstractController
{

    private static final Logger     _log                   = Logger.getLogger(FileUploadController.class);

    /**
     * @Fields ORIG_FOLDER : 原始存储文件夹
     */
    private final static String     ORIG_FOLDER            = "orig";

    private final static String     DEFAULT_ROOT           = "/upload";

    /**
     * @Fields DEFAULT_FILENAME_SPLIT : 文件名分隔符
     */
    private static final String     DEFAULT_FILENAME_SPLIT = "_";

    @Autowired()
    private RechargeableCardService rechargeableCardService;

    /**
     * 远程采集图片保存关系信息 <br/>
     * <p>
     * Description: 接收新增页面提交的数据，通过接口服务新增了图集数据 <br/>
     * <p>
     * Author: luojianhong<br/>
     * <p>
     * Date: 2013-5-11-上午10:54:52<br/>
     * <p>
     * 
     * @param request
     * @return 以ajax方式返回处理结果，格式为map结构
     * @throws IOException
     * @throws MalformedURLException
     * 
     */
    @RequestMapping("/remoteImage")
    @ResponseBody
    public Map<String, String> RemoteImage(HttpServletResponse response) throws MalformedURLException, IOException
    {
        if (_log.isInfoEnabled())
        {
            _log.info("operatorId=" + getOperatorId() + "|desc=远程图片抓取开始");
        }

        // request 必须携带的参数
        String prefix = request.getParameter("prefix");
        String id = request.getParameter("id");
        String root = request.getParameter("root");

        if (StringUtils.isBlank(prefix))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("operatorId=" + getOperatorId() + "|desc=图片上传,图片前缀为空");
            }
            prefix = "";
        }

        if (StringUtils.isBlank(id))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("operatorId=" + getOperatorId() + "|desc=图片上传,图片资源id为空");
            }
            id = "0";
        }

        if (StringUtils.isNotBlank(root))
        {
            try
            {
                root = getConfigByKey(root);
            }
            catch (UppDataBaseException e)
            {
                root = DEFAULT_ROOT;
                _log.error("operatorid=" + getOperatorId() + "|stackTrace=" + ExceptionUtils.getStackTrace(e));
            }
        }
        else
        {
            root = DEFAULT_ROOT;
        }

        String savePath = root + File.separator + getFolderDate() + File.separator + id + File.separator + ORIG_FOLDER;
        String dbStorePath = getFolderDate() + File.separator + id + File.separator + ORIG_FOLDER;

        String url = request.getParameter("upfile");
        String state = "远程图片抓取成功！";
        String[] arr = url.split("ue_separate_ue");
        String[] outSrc = new String[arr.length];
        for (int i = 0; i < arr.length; i++)
        {
            if (_log.isInfoEnabled())
            {
                _log.info("远程图片URI=" + arr[i]);
            }
            // 格式验证
            String type = getFileType(arr[i]);// 判断文件上传的类型.
            if (type.equals(""))
            {
                state = "图片类型不正确！";
                continue;
            }
            // String saveName = Long.toString(new Date().getTime()) + type;
            String saveName = prefix + DEFAULT_FILENAME_SPLIT + session.getId() + DEFAULT_FILENAME_SPLIT
                    + System.currentTimeMillis() + type;
            // 大小验证
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection conn = (HttpURLConnection) new URL(arr[i]).openConnection();
            if (conn.getContentType().indexOf("image") == -1)
            {
                state = "请求地址头不正确";
                continue;
            }
            if (conn.getResponseCode() != 200)
            {
                state = "请求地址不存在！";
                continue;
            }
            File dir = new File(savePath);
            if (!dir.exists())
            {
                dir.mkdirs();
            }
            File savetoFile = new File(savePath + File.separator + saveName);
            outSrc[i] = dbStorePath + File.separator + saveName;
            try
            {
                InputStream is = conn.getInputStream();
                OutputStream os = new FileOutputStream(savetoFile);
                int b;
                while ((b = is.read()) != -1)
                {
                    os.write(b);
                }
                os.close();
                is.close();
            }
            catch (Exception e)
            {
                if (_log.isInfoEnabled())
                {
                    _log.info("operatorId=" + getOperatorId() + "|desc=远程图片抓取失败");
                }
                _log.error(ExceptionUtils.getStackTrace(e));
                System.err.println("页面无法访问");
            }
        }

        String outstr = "";
        for (int i = 0; i < outSrc.length; i++)
        {
            outstr += outSrc[i] + "ue_separate_ue";
        }
        outstr = outstr.substring(0, outstr.lastIndexOf("ue_separate_ue"));

        Map<String, String> respMap = new HashMap<String, String>();
        respMap.put("url", outstr.replaceAll("\\\\", "/"));
        respMap.put("tip", state);
        respMap.put("srcUrl", url);

        return respMap;
    }

    /**
     * 图片上传(ajax) <br/>
     * <p>
     * Description: 接收新增页面提交的数据，上传图片 <br/>
     * <p>
     * Author: luojianhong<br/>
     * <p>
     * Date: 2013-5-11-上午10:54:52<br/>
     * <p>
     * 
     * @param request
     * @return 以ajax方式返回处理结果，格式为map结构
     * @throws Exception
     * 
     */
    @RequestMapping("/imageUp")
    @ResponseBody
    public Map<String, String> imageUp(HttpServletResponse response)
    {
        if (_log.isInfoEnabled())
        {
            _log.info("operatorId=" + getOperatorId() + "|desc=图片上传开始");
        }

        String savePath = "";
        String apachePath = "";
        String dBstorePath = "";
        // request 必须携带的参数
        String prefix = request.getParameter("prefix");
        String id = request.getParameter("id");
        String root = request.getParameter("root");
        String dirPrefix = request.getParameter("dirPrefix");
        String module = "";
        String dataFolder = request.getParameter("dataFolder");

        if (StringUtils.isBlank(prefix))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("operatorId=" + getOperatorId() + "|desc=图片上传,图片前缀为空");
            }
            prefix = "";
        }

        if (StringUtils.isBlank(id))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("operatorId=" + getOperatorId() + "|desc=图片上传,图片资源id为空");
            }
            id = "0";
        }

        if (StringUtils.isBlank(root))
        {
            root = DEFAULT_ROOT;
        }

        // 如果传入的参数有dirPrefix则使用传入的dirPrefix，没有则使用root参数然后截取模块名
        if (StringUtils.isNotBlank(dirPrefix))
        {
            module = dirPrefix;
        }
        else
        {
            if (StringUtils.contains(root, DEFAULT_FILENAME_SPLIT))
            {
                module = root.substring(0, root.indexOf(DEFAULT_FILENAME_SPLIT));
            }
        }

        try
        {
            root = getConfigByKey(root);
        }
        catch (UppDataBaseException e)
        {
            root = DEFAULT_ROOT;
            _log.error("operatorid=" + getOperatorId() + "|stackTrace=" + ExceptionUtils.getStackTrace(e));
        }

        // 根据参数判断是否在图片存储路径上添加日期
        if (StringUtils.isNotBlank(dataFolder))
        {
            savePath = root + File.separator + module + File.separator + dataFolder + File.separator + id
                    + File.separator + ORIG_FOLDER;
            dBstorePath = module + File.separator + dataFolder + File.separator + id + File.separator + ORIG_FOLDER;
        }
        else
        {
            savePath = root + File.separator + module + File.separator + id + File.separator + ORIG_FOLDER;
            dBstorePath = module + File.separator + id + File.separator + ORIG_FOLDER;
        }

        UploaderHelper up = new UploaderHelper(request);
        up.setSavePath(savePath);
        String[] fileType =
        { ".png", ".jpg", ".jpeg", ".gif" };
        up.setAllowFiles(fileType);
        up.setMaxSize(5120); // 单位KB
        up.setJsessionid(session.getId());
        up.setPrefix(prefix);
        up.setdBstorePath(dBstorePath);
        up.upload();

        if ("SUCCESS".equals(up.getState()))
        {
            if (_log.isInfoEnabled())
            {
                _log.info("operatorId=" + getOperatorId() + "|desc=图片上传成功");
            }
        }
        else
        {
            _log.error("operatorId=" + getOperatorId() + "|desc=图片上传失败|stackTrace=" + up.getState());
        }

        Map<String, String> respMap = new HashMap<String, String>();
        respMap.put("original", up.getOriginalName());
        respMap.put("url", up.getUrl().replaceAll("\\\\", "/"));
        respMap.put("title", up.getTitle());
        respMap.put("state", up.getState());
        respMap.put("apache", apachePath);

        return respMap;
    }

    /**
     * 得到模块代码 <br/>
     * <p>
     * Description: 返回当前操作的模块code <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-26-下午5:04:00<br/>
     * <p>
     * 
     * @return 模块代码
     * 
     */
    public List<File> getFiles(String realpath, List<File> files)
    {
        File realFile = new File(realpath);
        if (realFile.isDirectory())
        {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles)
            {
                if (file.isDirectory())
                {
                    getFiles(file.getAbsolutePath(), files);
                }
                else
                {
                    if (!getFileType(file.getName()).equals(""))
                    {
                        files.add(file);
                    }
                }
            }
        }
        return files;
    }

    /**
     * 得到模块代码 <br/>
     * <p>
     * Description: 返回当前操作的模块code <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-26-下午5:04:00<br/>
     * <p>
     * 
     * @return 模块代码
     * 
     */
    public String getFileType(String fileName)
    {
        String[] fileType =
        { ".png", ".jpg", ".jpeg", ".gif" };
        Iterator<String> type = Arrays.asList(fileType).iterator();
        while (type.hasNext())
        {
            String t = type.next();
            if (fileName.endsWith(t))
            {
                return t;
            }
        }
        return "";
    }

    /**
     * 得到模块代码 <br/>
     * <p>
     * Description: 返回当前操作的模块code <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-26-下午5:04:00<br/>
     * <p>
     * 
     * @return 模块代码
     * 
     */
    public String getRealPath(String path)
    {
        ServletContext application = request.getSession().getServletContext();
        String str = application.getRealPath(request.getServletPath());
        return new File(str).getParent();
    }

    /**
     * 获得文件夹日期 <br/>
     * <p>
     * Description: 获得文件夹格式的日期 yyyyMMdd <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-5-14-下午1:40:55<br/>
     * <p>
     * 
     * @return
     * 
     */
    private String getFolderDate()
    {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        return formater.format(new Date());
    }

    /**
     * 
     * 文件上传(异步调用) <br/>
     * <p>
     * Description: 文件上传(详细描述) <br/>
     * <p>
     * Author: yangzq<br/>
     * <p>
     * Date: 2013-7-3-上午9:12:00<br/>
     * <p>
     * 
     * @param test
     * @param multipartRequest
     * @return
     * 
     */
    @RequestMapping("/fileUpload")
    @ResponseBody
    public void fileUpload(HttpServletResponse response)
    {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart)
        {
            writeJsonObject(request, response, "{msgDesc:\"媒体文件为空\",msgType:\"info\",opResult:\"0\"}");
            return;
        }

        // request 必须携带的参数
        String prefix = request.getParameter("prefix");
        String id = request.getParameter("resourceId");
        String root = request.getParameter("rootDir");
        String dataFolder = request.getParameter("initDate");

        String savePath = "";
        String url = "";
        String dBstorePath = "";
        String originalName = "";
        String newName = "";
        String result = "";
        String msgType = "error";
        String opResult = "1";

        if (StringUtils.isNotBlank(root))
        {
            try
            {
                root = getConfigByKey(root);
            }
            catch (UppDataBaseException e)
            {
                root = DEFAULT_ROOT;
                _log.error("operatorid=" + getOperatorId() + "|stackTrace=" + ExceptionUtils.getStackTrace(e));
            }
        }
        else
        {
            root = DEFAULT_ROOT;
        }
        // 根据参数判断是否在图片存储路径上添加日期
        if (StringUtils.isNotBlank(dataFolder))
        {
            savePath = root + File.separator + dataFolder + File.separator + id + File.separator + ORIG_FOLDER;
            dBstorePath = dataFolder + File.separator + id + File.separator + ORIG_FOLDER;
        }
        else
        {
            savePath = root + File.separator + id + File.separator + ORIG_FOLDER;
            dBstorePath = id + File.separator + ORIG_FOLDER;
        }
        File dirFile = new File(savePath);
        if (!dirFile.exists())
        {
            dirFile.mkdirs();
        }

        DiskFileItemFactory dff = new DiskFileItemFactory();
        dff.setRepository(new File(savePath));

        try
        {
            if (_log.isInfoEnabled())
            {
                _log.info("开始上传文件");
            }

            ServletFileUpload sfu = new ServletFileUpload(dff);
            sfu.setSizeMax(51200 * 1024);
            sfu.setHeaderEncoding("utf-8");
            FileItemIterator fii = sfu.getItemIterator(request);

            while (fii.hasNext())
            {
                FileItemStream fis = fii.next();
                if (!fis.isFormField())
                {
                    originalName = fis.getName().substring(
                            fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
                    newName = getName(prefix, originalName);
                    url = dBstorePath + File.separator + newName;
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    FileOutputStream out = new FileOutputStream(new File(savePath + File.separator + newName));
                    BufferedOutputStream output = new BufferedOutputStream(out);
                    Streams.copy(in, output, true);
                }
            }

            result = "文件上传成功";
            msgType = "info";
            opResult = "0";

            if (_log.isInfoEnabled())
            {
                _log.info(result);
            }
        }
        catch (SizeLimitExceededException e)
        {
            result = "文件超过最大限制50M";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (FileUploadException e)
        {
            result = "文件上传异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (IOException e)
        {
            result = "文件上传IO异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (Exception e)
        {
            result = "未知异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }

        writeJsonObject(request, response, "{msgDesc:\"" + result + "\",msgType:\"" + msgType + "\",opResult:\""
                + opResult + "\",addr:\"" + url.replaceAll("\\\\", "/") + "\"}");
    }

    /**
     * 
     * 文件上传，读取号码文件入库(异步调用) <br/>
     * <p>
     * Description: 文件上传，读取号码文件入库(详细描述) <br/>
     * <p>
     * Author: yangzq<br/>
     * <p>
     * Date: 2013-7-3-上午9:12:00<br/>
     * <p>
     * 
     * @param test
     * @param multipartRequest
     * @return
     * 
     */
    @RequestMapping("/readFile")
    @ResponseBody
    public void readFile(HttpServletResponse response)
    {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart)
        {
            writeJsonObject(request, response, "{msgDesc:\"选择文件为空\",msgType:\"info\",opResult:\"0\"}");
            return;
        }
        String result = "";
        List<String> errorlist=  new ArrayList<String>();
        int totalCount=0;
        int successCount=0;
        int eroorCount = 0;
        String errorCardNums="";
        String msgType = "error";
        String opResult = "1";
        String url = "";
        String savePath = request.getSession().getServletContext().getRealPath("/") + "\\upload\\";
        System.out.println("savePath=" + savePath);
        File dirFile = new File(savePath);
        if (!dirFile.exists())
        {
            dirFile.mkdirs();
        }

        DiskFileItemFactory dff = new DiskFileItemFactory();
        dff.setRepository(new File(savePath));

        try
        {
            if (_log.isInfoEnabled())
            {
                _log.info("开始上传文件");
            }
            ServletFileUpload sfu = new ServletFileUpload(dff);
            sfu.setSizeMax(51200 * 1024);
            sfu.setHeaderEncoding("utf-8");
            FileItemIterator fii = sfu.getItemIterator(request);
            String prefix ="";
            String fileName="";
            String newFileName = "";
            while (fii.hasNext())
            {
                FileItemStream fis = fii.next();
                if (!fis.isFormField())
                {
                    fileName = fis.getName();
                    prefix= fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
//                    System.out.println("prefix="+prefix);
                    newFileName =  System.currentTimeMillis() +DataMatrixUtil.randomNumber()+prefix;
                    url = savePath + newFileName;
//                    System.out.println("url=" + url);
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    FileOutputStream out = new FileOutputStream(new File(url));
                    BufferedOutputStream output = new BufferedOutputStream(out);
                    Streams.copy(in, output, true);
                }
            }

            List<String> list = null;
            if (prefix.endsWith(".xls") || prefix.endsWith(".xlsx"))
            {
                list = ExcelUtil.readExcelByFirstRow(url);
            }
            else if (prefix.endsWith(".txt"))
            {
                list = TxtUtil.readTxtFile(url);
            }
            try
            {
                if(list!=null && list.size()>0){
                    totalCount = list.size();
                    list = removeDuplicate(list);
                    errorlist = rechargeableCardService.batchAdd(list, getOperatorId());
                    if(errorlist!=null && errorlist.size()>0){
                        eroorCount = errorlist.size();
                    }
                    if(list!=null && list.size()>0){
                        successCount = list.size() - eroorCount;
                    }
                }
                
                for (String str : errorlist)
                {
                    if("".equals(errorCardNums)){
                        errorCardNums = str;
                    }else{
                        errorCardNums = errorCardNums+","+str;
                    }
                }
//                System.out.println("errorCardNums:" + errorCardNums);
            }
            catch (IccardDatabaseException e)
            {
                _log.error(ExceptionUtils.getStackTrace(e));
            }
            catch (Exception e)
            {
                _log.error(ExceptionUtils.getStackTrace(e));
            }
            if(totalCount>0 && successCount>0){
                result = "批量入库成功!";
                msgType = "info";
                opResult = "0";
            }else if(totalCount==0){
                result = "批量入库失败,号码文件为空!";
                msgType = "info";
                opResult = "1";
            }else  if(totalCount>0 && successCount==0){
                result = "批量入库失败,文件号码无效!";
                msgType = "info";
                opResult = "2";
            }

            if (_log.isInfoEnabled())
            {
                _log.info(result);
            }
        }
        catch (SizeLimitExceededException e)
        {
            result = "文件超过最大限制50M";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (FileUploadException e)
        {
            result = "文件上传异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (IOException e)
        {
            result = "文件上传IO异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (Exception e)
        {
            result = "未知异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        writeJsonObject(request, response, "{msgDesc:\"" + result + "\",msgType:\"" + msgType + "\",opResult:\""
                + opResult+ "\",errorCardNums:\"" + errorCardNums+ "\",successCount:\"" + successCount+ "\",eroorCount:\"" + eroorCount+ "\",totalCount:\"" + totalCount + "\",addr:\"" + url.replaceAll("\\\\", "/") + "\"}");
    }
    
    private static List<String> removeDuplicate(List<String> list)
    {
        for (int i = 0; i < list.size() - 1; i++)
        {
            for (int j = list.size() - 1; j > i; j--)
            {
                if (list.get(j).equals(list.get(i)))
                {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    /**
     * 
     * 向客户端响应json数据 <br/>
     * <p>
     * Description: 向客户端响应json数据 <br/>
     * <p>
     * Author: yangzq<br/>
     * <p>
     * Date: 2013-7-3-下午1:57:18<br/>
     * <p>
     * 
     * @param request
     * @param resp
     * @param jsonData
     * 
     */
    private void writeJsonObject(HttpServletRequest request, HttpServletResponse resp, String jsonData)
    {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = null;
        try
        {
            pw = resp.getWriter();
            pw.print(jsonData);
            pw.flush();
        }
        catch (IOException e)
        {
            handleException(e);
        }
        finally
        {
            if (null != pw)
            {
                pw.close();
            }
        }
    }

    /**
     * 得到文件名称 <br/>
     * <p>
     * Description: 依据原始文件名生成新文件名 <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-5-14-上午11:24:26<br/>
     * <p>
     * 
     * @param fileName
     * @return
     * 
     */
    private String getName(String prefix, String fileName)
    {
        if (StringUtils.isNotBlank(prefix))
        {
            return prefix + DEFAULT_FILENAME_SPLIT + session.getId() + DEFAULT_FILENAME_SPLIT
                    + System.currentTimeMillis() + this.getFileExt(fileName);
        }

        return session.getId() + DEFAULT_FILENAME_SPLIT + System.currentTimeMillis() + this.getFileExt(fileName);
    }

    /**
     * 获取文件扩展名
     * 
     * @return string
     */
    private String getFileExt(String fileName)
    {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 得到模块代码 <br/>
     * <p>
     * Description: 返回当前操作的模块code <br/>
     * <p>
     * Author: yun<br/>
     * <p>
     * Date: 2013-4-26-下午5:04:00<br/>
     * <p>
     * 
     * @return 模块代码
     * 
     */
    @Override
    public String getMouduleCode()
    {
        return ModuleEnum.FileUpload.moduleName.value;
    }
}